package com.charon.auth.demo.controller;

import com.charon.common.entity.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
  *@ClassName: FileController
  *@Description: 文件上传Controller
  *@Author: Charon [248135724@qq.com]
  *@Date: 2019/1/14 0014 11:04
  *@Version: 1.0
  */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    String folder="E:\\";

    @PostMapping
    public FileInfo uploadFile(MultipartFile testFile) throws IOException {
        log.info("文件上传："+testFile.getName());
        log.info(testFile.getName());
        log.info(testFile.getOriginalFilename());
        File localFile=new File(folder,new Date().getTime()+".txt");
        testFile.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{name}")
    public void download(@PathVariable String name, HttpServletRequest request, HttpServletResponse response){
        log.info("文件下载");
        try (InputStream is = new FileInputStream(new File(folder, name + ".txt"))) {
            try (OutputStream os = response.getOutputStream()) {
                response.setContentType("application/x-download");
                response.addHeader("Content-Disposition","attachment;filename-test.txt");
                IOUtils.copy(is,os);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
